import { QMainWindow, QWidget, QMessageBox, QLabel, FlexLayout, QPushButton } from '@nodegui/nodegui';
import * as child from 'child_process';
import path from 'path'
import fs from 'fs'

import { createImage, createLabel, createCheckboxList, createSearchContainer, createRadioList } from './components'

import logo from '../assets/content-logo.png';
import xiao from '../assets/xiao.png';

const wList = [
  { key: '0', v: '窗口1' },
  { key: '1', v: '窗口2' },
  { key: '2', v: '窗口3' },
  { key: '3', v: '窗口4' },
  { key: '4', v: '窗口5' },
]
const windowsGroupBox = createRadioList(wList, 'radioBox')

const mList = [
  { key: '1', v: '挖矿' },
  { key: '2', v: '养鸡' },
  { key: '3', v: '种地' },
  { key: '4', v: '养牛' },
  { key: '5', v: '建造' },
  { key: '6', v: '自动售卖' },
]
const moduleGroupBox = createCheckboxList(mList, 'groupBox')

const tList = [
  { key: 'milk', v: '牛奶' },
  { key: 'barley', v: '麦子' },
  { key: 'corn', v: '玉米' },
  { key: 'chicken', v: '鸡' },
  { key: 'calf', v: '乳牛' },
  { key: 'egg', v: '鸡蛋' },
]
const typeGroupBox = createCheckboxList(tList, 'groupBox2')
typeGroupBox.hide()

for (const m of mList) {
  if (m.key == '6') {
    const r1 = m['o']
    if (r1) {
      r1.addEventListener("clicked", () => {
        if (r1.isChecked()) {
          typeGroupBox.show()
        } else {
          typeGroupBox.hide()
        }
      })
    }
  }
}


let search = ''
const searchErrorInfo = new QLabel();
searchErrorInfo.setObjectName('errorInfo');
searchErrorInfo.hide()
let comboBox
const searchContainer = createSearchContainer((searchText, combo) => {
  comboBox = combo
  if (searchText.includes('.wam')) {
    search = searchText
    searchErrorInfo.hide()
  } else if (/[a-z1-5]{12}/.test(searchText)) {
    search = searchText
    searchErrorInfo.hide()
  } else {
    search = ''
    searchErrorInfo.setText('账号格式错误!');
    searchErrorInfo.show()
  }
});


const button = new QPushButton();
button.setText("一键启动");
button.setObjectName("but");
button.addEventListener('clicked', async () => {

  if (!search) {
    searchErrorInfo.setText('必须填写正确的钱包地址，比如：abcdf.wam');
    searchErrorInfo.show()
    return;
  } else {
    comboBox.addItem(undefined, search);
  }

  let windowCmd = ''
  let moduleCmd = ''
  let typeCmd = ''
  for (const m of wList) {
    const r = m['o']
    if (r.isChecked()) {
      const key = wList.find(e => e.v == r.text())
      windowCmd += key?.key
    }
  }

  for (const m of mList) {
    const r = m['o']
    if (r.isChecked()) {
      const key = mList.find(e => e.v == r.text())
      moduleCmd += key?.key
    }
  }

  for (const m of tList) {
    const r = m['o']
    if (r.isChecked()) {
      const key = tList.find(e => e.v == r.text())
      if (key) {
        typeCmd += (key?.key + '-')
      }
    }
  }
  typeCmd = typeCmd.length ? typeCmd.substring(0, typeCmd.length - 1) : typeCmd
  if (!windowCmd) {
    searchErrorInfo.setText('请选择窗口的位置！');
    searchErrorInfo.show()
    return;
  }
  if (!moduleCmd) {
    searchErrorInfo.setText('请选择开启的模块，可多选！');
    searchErrorInfo.show()
    return;
  }
  if (process.platform === 'darwin') {
    // for macos
    try {
      const tempSh = '/tmp/autoscripts.sh'
      const parameters = ['-a', 'Terminal', tempSh];
      const executablePath = path.resolve(process.cwd(), 'index');
      console.log(`${executablePath} ${search} ${windowCmd} ${moduleCmd} ${typeCmd}`);

      fs.writeFileSync(tempSh, `${executablePath} ${search} ${windowCmd} ${moduleCmd} ${typeCmd}`, {
        encoding: "utf8",
        mode: 0o755
      });
      const childspawn = child.spawn("open", parameters, {
        detached: true,
        stdio: 'ignore'
      });
      childspawn.unref();

    } catch (err) {
      console.log(err);
    }
  } else if (
    process.platform === 'win32' ||
    process.env.OSTYPE === 'cygwin' ||
    process.env.OSTYPE === 'msys'
  ) {
    // for win
    try {
      var executablePath = path.resolve(process.cwd(), 'index.exe');
      var parameters = ['/c', executablePath, search, windowCmd, moduleCmd, typeCmd];
      console.log(parameters);

      const childspawn = child.spawn("cmd.exe", parameters, {
        detached: true,
        stdio: 'ignore'
      });
      childspawn.unref();
    } catch (err) {
      console.log(err);
    }
  } else {
    // 
    console.log('linux');
  }

});

// =======================================================
// =======================================================
// =======================================================
// =======================================================

const win = new QMainWindow();
win.setWindowTitle("农民世界 一键挂机 v2.0");

const centralWidget = new QWidget();
centralWidget.setObjectName("main");
const rootLayout = new FlexLayout();
centralWidget.setLayout(rootLayout);

rootLayout.addWidget(createImage(logo, 185.5, 90));
rootLayout.addWidget(createLabel('设置账号', 'title'));
rootLayout.addWidget(searchContainer);

rootLayout.addWidget(windowsGroupBox);
rootLayout.addWidget(moduleGroupBox);
rootLayout.addWidget(typeGroupBox);

rootLayout.addWidget(button);
rootLayout.addWidget(searchErrorInfo);
rootLayout.addWidget(createImage(xiao, 100, 100, 'weixinlogo'));
rootLayout.addWidget(createLabel('技术支持微信：thegamefi', 'weixin'));

win.setCentralWidget(centralWidget);
win.setStyleSheet(
  `
    #main {
      padding: 10px;
      background-color: #009688;
      height: '100%';
      align-items: 'center';
      justify-content: 'center';
    }
    #title {
      font-size: 22px;
      font-weight: bold;
      padding: 5px 0;
    }
    #errorInfo {
      color: red;
      padding-bottom: 10px;
    }
    #but {
      padding: 10px 0;
    }
    #searchInput{
    }
    #weixinlogo {
    }
    #weixin {
      margin: 5px;
    }
    #radioBox{
      margin: 10px;
      flex-direction: 'row';
    }
    #groupBox{
      margin: 10px;
      flex-direction: 'row';
    }
    #groupBox2{
      margin: 10px;
      flex-direction: 'row';
    }
  `
);

win.resize(400, 580);
win.show();

(global as any).win = win;
